package com.zzz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzz.user.dao.UPermissionMapper;
import com.zzz.user.dao.URoleMapper;
import com.zzz.user.dao.UUserMapper;
import com.zzz.user.entity.URole;
import com.zzz.user.entity.UUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
public class UserConfigService implements UserDetailsService, ClientDetailsService {

    @Autowired
    private UUserMapper userMapper;
    @Autowired
    private URoleMapper roleMapper;
    @Autowired
    private UPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        UUser user = userMapper.selectOne(new QueryWrapper<UUser>().eq("phone",phone));
        if (user == null) return null;
        List<URole> roles = roleMapper.selectList(new QueryWrapper<URole>().eq("user_id", user.getId()));
        List<String> codeList = permissionMapper.getCodeByRoleIds(roles.stream().map(x->x.getId()).collect(Collectors.toList()));
        UserDetails details = User.withUsername(phone).password(user.getPassword())
                .authorities(codeList.stream().toArray(String[]::new)).build();
        return details;
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        // TODO 查询client
        BaseClientDetails details = new BaseClientDetails();
        details.setClientId(UUID.randomUUID().toString()); // client_id
//        details.setClientSecret();
        return details;
    }
}
